package com.data.common.util;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;

/**
 * @ClassName: IuspTransport
 * @version 2.0
 * @Desc: 加密对象
 * @author huhuaping
 * @date 2019年11月12日上午11:39:32
 * @history v2.0
 *
 */
public class DataSecurityUtil {

	private static final String	ALGO = "AES/ECB/PKCS7Padding";
    private static final String CHAR_SET_NAME="UTF-8"; //字符编码

    static {
        //BouncyCastle是一个开源的加解密解决方案，主页在http://www.bouncycastle.org/
        Security.addProvider(new BouncyCastleProvider());
    }


    /**
     * 根据密钥和算法生成Key
     *
     * @return
     * @throws Exception
     */
    private static Key generateKey(byte[] keyValue) throws Exception {
        Key key = new SecretKeySpec(keyValue, ALGO);
        return key;
    }

    /**
     *
     * 描述：加密
     * @author huhuaping
     * @date 2019年11月12日下午1:52:40
     * @param data
     * @param secretKey
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String secretKey) throws Exception {
    	 Key key = generateKey( secretKey.getBytes());
         Cipher c = Cipher.getInstance(ALGO);
         c.init(Cipher.ENCRYPT_MODE, key);

         byte[] encVal = c.doFinal(data.getBytes(CHAR_SET_NAME));
         byte[] byteArr= Base64.encodeBase64(encVal);
 		String encryptedValue=new String(byteArr);
         return encryptedValue;

    }


    /**
     *
     * 描述：解密
     * @author huhuaping
     * @date 2019年11月12日下午1:51:02
     * @param data
     * @param secretKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String data, String secretKey) throws Exception {

    	 Key key = generateKey(secretKey.getBytes());

         Cipher c = Cipher.getInstance(ALGO);
         c.init(Cipher.DECRYPT_MODE, key);
         byte[] decodedValue= Base64.decodeBase64(data.getBytes(CHAR_SET_NAME));
         byte[] decValue = c.doFinal(decodedValue);
         String decryptedValue = new String( decValue,CHAR_SET_NAME);

         return decryptedValue;
    }


    public static String generateMcuSecretKey(String mac, long t) {
//		String start = getStringFormatData(mac, 12);
        String	end = String.valueOf(t + 27839);
        String key= mac + end.substring(end.length() - 4);

        if(key.length()<16){
            return getStringFormatData("", 16-key.length())+key;
        }else{
            return key.substring(key.length()-16);
        }

    }


    /**
     * @return 返回一个指定格式补0的String
     * @Desc 获取一个格式话的数据
     */
    public static String getStringFormatData(String mac, int length) {
        String format = "%0" + length + "d";
        return String.format(format, mac);
    }



}
